package com.aijk.commons.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Freemarker模板引擎工具类
 * 
 * @author ChenDeWei
 * 
 */
public class FreemarkerUtils {

	private static Configuration cfg = new Configuration();
	private static StringTemplateLoader stringLoader = new StringTemplateLoader();

	@SuppressWarnings("unchecked")
	public static String format(String content, Object obj) throws IOException, TemplateException {
		stringLoader.putTemplate("str", content);
		cfg.setTemplateLoader(stringLoader);
		Template template = cfg.getTemplate("str", "utf-8");

		StringWriter writer = new StringWriter();

		Map<String, Object> root = null;

		template.process(obj, writer);

		return writer.toString();

	}
	
	@SuppressWarnings("unchecked")
	public static String fileFormat(String filename, Object obj) throws IOException, TemplateException {
		String path = FreemarkerUtils.class.getResource("/template").getPath();
		cfg.setDirectoryForTemplateLoading(new File(path));  
		Template template = cfg.getTemplate(filename, "utf-8");
			
		StringWriter writer = new StringWriter();

		Map<String, Object> root = null;
		JSONObject jsonObject = null;
		if (obj instanceof JSONObject) {
			jsonObject = (JSONObject) obj;
		} else {
			String jsonStr = JSON.toJSONString(obj);
			jsonObject = JSONObject.parseObject(jsonStr);
		}
		root = JSON.parseObject(jsonObject.toJSONString(), HashMap.class);
		template.process(root, writer);

		return writer.toString();

	}


}
